<?php

namespace app\listener\worker;

use app\services\worker\WorkerTokenServices;
use crmeb\interfaces\ListenerInterface;

class WorkerToken implements ListenerInterface
{
    /**
     * 登录完成 后置事件
     * @param $event
     * @return void
     */
    public function handle($event): void
    {
        [$worker_id, $token, $device_type] = $event;

        /** @var WorkerTokenServices $workerTokenServices */
        $workerTokenServices = app()->make(WorkerTokenServices::class);

        $where = [];
        $where[] = ['worker_id', '=', $worker_id];
        $where[] = ['device_type', '=', $device_type];
        /** @var WorkerTokenServices $findWorkerToken */
        $findWorkerToken = $workerTokenServices->getOne($where);

        $currentTime = time();
        $expireTime = $currentTime + 24 * 3600 * 180;

        if (empty($findWorkerToken)) {
            $arr = [];
            $arr['token'] = $token;
            $arr['expire_time'] = $expireTime;
            $arr['create_time'] = $currentTime;
            $arr['device_type'] = $device_type;
            $arr['worker_id'] = $worker_id;
            $workerTokenServices->save($arr);
        } else {
            $workerTokenServices->update($findWorkerToken->id, [
                'token' => $token,
                'expire_time' => $expireTime,
                'create_time' => $currentTime
            ]);
        }
    }
}
